# 为menu提供数据转化服务
from django.core.cache import cache
from django.db import transaction
from django.http import JsonResponse
from django.shortcuts import render

from apps.config.models import Menu_model
from apps.config.serializers import Menu_serializer
from apps.users.models import Users_model


def Rec_Tree(datas):
    lists = []
    tree = {}
    parent_id = ''
    for i in datas:
        item = i
        tree[item['id']] = item
    root = None
    for i in datas:
        obj = i
        if not obj['menu_pid']:
            root = tree[obj['id']]
            lists.append(root)
        else:
            parent_id = obj['menu_pid']
            if 'children' not in tree[parent_id]:
                tree[parent_id]['children'] = []
            tree[parent_id]['children'].append(tree[obj['id']])
    return lists
def menus_list(request):
    # 获得登录的用户名
    code = request.user
    # 通过user查找正常显示存在的role角色的id
    user_obj = Users_model.objects.get(user_code=code)
    role_list = user_obj.user_role.filter().values_list('id', flat=True)
    # 通过角色查拥有的菜单权限,所拥有的目录，菜单权限，用以前台渲染数据
    list2 = Menu_model.objects.filter(role_model__id__in=role_list).distinct().exclude(menu_marital='03').order_by('menu_code')
    # 这里用以查询他对于表单拥有的操作权限
    list3 = Menu_model.objects.filter(role_model__id__in=role_list).distinct().exclude(menu_marital__in = ['01','02'])
    menu_obj = Menu_serializer(list2, many=True)
    menu_obj1 = Menu_serializer(list3, many=True)
    rec_list = Rec_Tree(menu_obj.data)
    return JsonResponse({'code': '0', 'data': rec_list,'data1':menu_obj1.data})
# 此时图对应后台管理中choice的视图
def menus_lists(request):
    list3 = Menu_model.objects.filter().exclude(menu_marital='03')
    menu_obj = Menu_serializer(list3, many=True)
    rec_list = Rec_Tree(menu_obj.data)
    return JsonResponse({'code': '0', 'data': rec_list})
# 获得nenu页面,取的数据
def menus_view(request):
    # 查询其页面操作权限
    # try:
    #     menu_list = Menu_model.objects.filter()
    # except Exception as e:
    #     return JsonResponse({'code':201,'msg':'menus_view视图出现问题'})
    # menus = Menu_serializer(menu_list,many=True)
    menu_list = cache.get('menu_list')
    menu_obj = Menu_serializer(menu_list, many=True)
    return render(request, 'menus/list.html', {'data1':menu_obj.data})

# 后台设置menu需要
def menus_list1(request):
    try:
        menus = Menu_model.objects.filter()
        count = Menu_model.objects.count()
    except Exception as e:
        return JsonResponse({'code':0,'msg':'后台menu列表出现问题！'})
    list=[]
    for i in menus:
        pid_list=Menu_model.objects.filter(pk=i.menu_pid_id).values_list('tree_name',flat=True)
        if len(pid_list) == 0:
            pid_menu = None
        else:
            pid_menu = pid_list[0]
        dict={}
        dict['id'] = i.id
        dict['menu_code']=i.menu_code
        dict['tree_name']=i.tree_name
        dict['href']=i.href
        dict['fontFamily']=i.fontFamily
        dict['icon']=i.icon
        dict['menu_marital']=i.menu_marital
        dict['menu_pname']=pid_menu
        dict['spread']=i.spread
        dict['now_status'] = i.now_status
        dict['menu_pid']=i.menu_pid_id
        list.append(dict)
    return JsonResponse({'code': 0, 'mes': '成功！', 'count': count, 'data': list})


# 添加menus页面
def menus_insert_view(request):
    return render(request, 'menus/insert.html')


# 菜单添加动作
@transaction.atomic
def menus_insert(request):
    # 先得判断是否具有添加权限（50500201）
    m_list = cache.get('menu_list')
    per_list = []
    for i in m_list:
        per_list.append(i.menu_code)
    # 判断其是否拥有权限
    if '50500201' not in per_list:
        return JsonResponse({'code': 201, 'msg': '您无此权限，请联系管理员！'})
    spoint_1 = transaction.savepoint()  # 可以设置多个保存点
    code = request.POST.get('menu_code')
    name = request.POST.get('tree_name')
    href = request.POST.get('href')
    marital = request.POST.get('menu_marital')
    if marital =='03':
        font = '/'
    else:
        font = request.POST.get('fontFamily')
    icon = request.POST.get('icon')
    marital = request.POST.get('menu_marital')
    spread = False
    pid = request.POST.get('select')
    status = request.POST.get('now_status')
    remark = request.POST.get('remark_describe')
    try:
        Menu_model.objects.create(menu_code=code, tree_name=name,href=href,fontFamily=font,icon=icon,menu_marital=marital,spread=spread, menu_pid_id=pid,
                                  now_status=status, remark_describe=remark,
                                  )
    except Exception as e:
        transaction.savepoint_rollback(spoint_1)  # 可以回滚到指定的保存点
        if e.args[0] == 1406:
            return JsonResponse({'code': 201, 'msg': '数据过长！'})
        if e.args[0] == 1062:
            return JsonResponse({'code': 202, 'msg': '唯一值出现重复！请检查菜单代码。'})
        else:
            transaction.savepoint_rollback(spoint_1)  # 可以回滚到指定的保存点
            return JsonResponse({'code': 203, 'msg': '未知错误！请联系管理员'})
    return JsonResponse({'code': 0, 'msg': '添加成功！'})

# menus修改页面
def menus_edit_view(request):
    return render(request,'menus/edit.html')

# menus修改动作
@transaction.atomic
def menus_edit(request,id):
    # 判断是否有权限id
    m_list = cache.get('menu_list')
    per_list = []
    for i in m_list:
        per_list.append(i.menu_code)
    if '50500202' not in per_list:
        return JsonResponse({'code': 201, 'msg': '您无此权限，请联系管理员！'})
    spoint_1 = transaction.savepoint()  # 可以设置多个保存点
    code = request.POST.get('menu_code')
    name = request.POST.get('tree_name')
    href = request.POST.get('href')
    font = request.POST.get('fontFamily')
    icon = request.POST.get('icon')
    marital = request.POST.get('menu_marital')
    spread=False
    menu_pid = request.POST.get('select')
    status = request.POST.get('now_status')
    # 为了保证数据库数据格式一致性，这里当为按钮时，FontFamily填为/
    if marital=='03':
        font='/'
    remark = request.POST.get('remark_describe')
    try:
        Menu_model.objects.filter(pk=id).update(menu_code=code, tree_name=name, href=href,fontFamily=font,icon=icon,menu_marital=marital,
                                                spread=spread,menu_pid_id=menu_pid,now_status=status,remark_describe=remark)
    except Exception as e:
        transaction.savepoint_rollback(spoint_1)  # 可以回滚到指定的保存点
        if e.args[0] == 1406:
            return JsonResponse({'code': 201, 'msg': '数据过长！'})
        if e.args[0] == 1062:
            return JsonResponse({'code': 202, 'msg': '唯一值出现重复！请检查菜单代码。'})
        else:
            transaction.savepoint_rollback(spoint_1)  # 可以回滚到指定的保存点
            return JsonResponse({'code': 203, 'msg': 'menu修改模块出现问题，请联系管理员！'})

    return JsonResponse({'code': 0, 'msg': '修改成功！'})

# menus删除动作
@transaction.atomic
def menus_del(request,id):
    # 判断是否有权限id
    m_list = cache.get('menu_list')
    per_list = []
    for i in m_list:
        per_list.append(i.menu_code)
    if '50500203' not in per_list:
        return JsonResponse({'code': 201, 'msg': '您无此权限，请联系管理员！'})
    spoint_1 = transaction.savepoint()  # 可以设置多个保存点
    try:
        Menu_model.objects.get(pk=id).delete()
    except Exception as e:
        transaction.savepoint_rollback(spoint_1)  # 可以回滚到指定的保存点
        return JsonResponse({'code': 202, 'msg': 'menus删除模块出现问题，请联系管理员！'})
    return JsonResponse({'code':0,'msg':'删除成功！'})

# 下拉框
def menus_list2(request):
    try:
        menu_list = Menu_model.objects.filter()
    except Exception as e:
        return JsonResponse({'code': 0, 'msg': '后台menu列表出现问题！'})
    ser_obj = Menu_serializer(menu_list, many=True)
    dept_lists = Rec_Tree(ser_obj.data)
    return JsonResponse({'code': 0, 'data': dept_lists})
